<template>
<div>
  <div class="table">
    <el-table stripe ref="multipleTable" height="350" :data="tableData" tooltip-effect="dark" style="width: 100%" size="small" :row-key="getRowKeys" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
      <el-table-column align="center"  prop="couponTitle" label="优惠券名称"></el-table-column>
      <el-table-column align="center"  prop="couponMoney" label="优惠券面值（元)" width="150"></el-table-column>
      <el-table-column align="center"  prop="couponConditionMoney" label="使用门槛"></el-table-column>
      <el-table-column align="center"  prop="expireDateInterval" label="券有效期"></el-table-column>
      <el-table-column align="center"  prop="oils" label="可用油品"></el-table-column>
      <el-table-column label="券数量" align="center" width="160" fixed="right">
        <template slot-scope="scope">
          <el-input-number size="mini" :value="scope.row.couponNum" @change="handleChange(scope.row, $event)" :min="1" :max="10" label="描述文字"></el-input-number>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageOptions.pageIndex" :page-sizes="pageSizes" :page-size="pageOptions.pageSize" layout="total, sizes, prev, pager, next" :total="allTotal">
      </el-pagination>
    </div>
    <div class="message">
      <div>
        <el-checkbox-group v-model="checkList" class="check">
          <el-checkbox label="1" :disabled="!smsBalance">发送短信通知 <span style="color: #A0A0A0;">当前剩余短信条数：{{smsBalance}}</span></el-checkbox>
          <el-checkbox label="2" :disabled="!pushBalance">发送APP消息通知 <span style="color: #A0A0A0;">当前剩余APP通知条数：{{pushBalance}}</span></el-checkbox>
        </el-checkbox-group>
      </div>
      <div>
        <el-checkbox v-model="pushSelf">是否给本账户发送消息通知</el-checkbox>
      </div>
      <!-- <div class="guess">
        <span>预计通知{{passParams.guessPeople}}人</span>
        <span>总计发券金额：{{allCash}}元</span>
      </div> -->
    </div>
    <div class="confirm">
      <el-button size="medium" @click="cancel">取消</el-button>
      <el-button size="medium" @click="handelToMessage" type="primary">确认</el-button>
    </div>
  </div>
  <el-dialog width="500px" center append-to-body title="为避免活动误发，向已绑定本账号的手机发送短信" :visible.sync="dialogMessageVisible">
    <div class="phone">将发送验证码给{{userInfo.mobile}}，请注意手机查收</div>
    <div class="mess">
      <el-input size="mini" type="text" style="width: 59%;margin-right: 12px" v-model="code" maxlength="4" autocomplete="off" placeholder="验证码"></el-input>
      <el-button @click="toSendCode" type="primary" :disabled="isSending" class="btn" :style="{height: '30px', padding: paddingType[0], backgroundColor: paddingType[1],borderRadius: '1px',border:'none', color: paddingType[2]} "><span style="font-size: 12px">{{codeText}}</span></el-button>
    </div>
    <div class="sumbit">
      <el-button size="mini" @click="handelMessage" type="primary">确认</el-button>
    </div>
  </el-dialog>
</div>
</template>

<script>
import { couponList, sendVerification, texHas, createAroundDriver, createLostDriver } from '@api/market'
import {mapGetters} from 'vuex'
export default {
  props: {
    passParams: {
      type: Object,
      default: () => ({})
    },
    multipleSelections: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      pushBalance: undefined, // app剩余条数
      smsBalance: undefined, // 短信剩余条数
      tableData: [],
      pageSizes: [10],
      pageOptions: {
        pageIndex: 1, // 当前页
        pageSize: 10 // 每页个数
      },
      allTotal: 0,
      checkList: [], // 短信和app通知
      pushSelf: false,
      multipleSelectionDia: [], // 选中的备用框
      code: '', // 验证码
      codeText: '获取验证码',
      isSending: false,
      dialogMessageVisible: false
    }
  },
  computed: {
    paddingType() {
      let { isSending } = this
      if (isSending) {
        return ['0', '#F4F4F5', '#4B7EFE']
      } else {
        return ['0 10px 0 10px', '#4B7EFE', '#fff']
      }
    },
    // 计算总金额， 商户券*数量相加 在 * 人数
    allCash () {
      const arr = this.multipleSelectionDia
      if (arr.length === 0) { return 0 }
       return arr.reduce((sum, next) => sum + (next.couponMoney * next.couponNum), 0) * this.passParams.guessPeople
    },
    ...mapGetters(['userInfo'])
  },
  methods: {
    // 取消按钮
    cancel() {
      this.$emit('handelClose')
    },
    // 绑定唯一选中值
    getRowKeys(row) {
      return row.id
    },
    // 记录选中值
    handleSelectionChange(val) {
      this.multipleSelectionDia = val;
    },
    // 切换页码
    handleCurrentChange(val) {
      this.pageOptions.pageIndex = val
      this.queryOrderList(this.passParams.gasId)
    },
    // 切换每页多少条数据
    handleSizeChange(val) {
      console.log(val) // 每页显示多少条改变时触发
    },
    // 计数器回调
    handleChange(row, val) {
      this.tableData.map(v => {
        if (row.id === v.id) {
          this.$set(v, 'couponNum', val) //通过$set设置数据集合里面的参数进行渲染
        }
      })
    },
    // 发送验证码
    toSendCode() {
      this.sendCode(this.userInfo.mobile)
    },
    // 确认按钮
    handelToMessage() {
      if (this.multipleSelectionDia.length === 0) {
        this.$message({ message: '请勾选优惠券', type: 'warning' })
        return
      }
      if (this.checkList.length === 0) {
        this.$message({ message: '请勾选通知方式', type: 'warning' })
        return
      }
      this.isPeople()
      this.dialogMessageVisible = true
    },
    // 判断当前选中的人数是否大于勾选的短信或者app通知条数
    isPeople () {
      const { checkList, passParams, pushBalance, smsBalance } = this
      const people = passParams.guessPeople
      if(checkList.length < 2 && checkList[0] === '1' && smsBalance < people) {
        this.$message({ message: '当前消息条数小于发券人数，将按照剩余消息条数发放优惠券', type: 'warning' })
      }
      if(checkList.length < 2 && this.checkList[0] === '2' && pushBalance < people) {
        this.$message({ message: '当前消息条数小于发券人数，将按照剩余消息条数发放优惠券', type: 'warning' })
      }
      if(checkList.length === 2) {
        const m = pushBalance > smsBalance ? pushBalance : smsBalance
        if(m < people && pushBalance < people) {
          this.$message({ message: '当前消息条数小于发券人数，将按照剩余消息条数发放优惠券', type: 'warning' })
        }
      }
    },
    // 最后的总确认按钮
    handelMessage () {
      if (this.code === '') {
        this.$message({ message: '请填写验证码', type: 'warning' })
        return
      }
      const couponData = this.multipleSelectionDia.map(item => {
        return {
          couponCode: item.couponCode,
          couponNum: item.couponNum
        }
      })
      this.passParams.couponListJson = JSON.stringify(couponData)
      this.passParams.mobile = this.userInfo.mobile
      this.passParams.code = this.code
      this.passParams.noticeWay = this.checkList.join(',')
      this.passParams.pushSelf = this.pushSelf
      if (this.type === 'around') {
        this.createAroundDriverApi(this.passParams)
      } else {
        this.createLostDriverApi(this.passParams)
      }
    },
    async sendCode(mobile) {
      try {
        const { code } = await sendVerification({ mobile })
        if (code !== 200) return
        this.isSending = true
        this.setCountText()
      } catch (error) {
        console.log(error.message)
      }
    },
    setCountText() {
      this.codeText = '60s后重新发送'
      let count = 60
      let timer = setInterval(() => {
        this.codeText = `${count}s后重新发送`
        if (count === 0) {
          clearInterval(timer)
          this.isSending = false
          this.codeText = '获取验证码'
        } else {
          count--
          this.codeText = `${count}s后重新发送`
        }
      }, 1000)
    },
    // 短信剩余条数
    async texHasApi(gasId) {
      try {
        const { code, result = {} } = await texHas({ gasId })
        if (code !== 200) return
        this.pushBalance = result.pushBalance
        this.smsBalance = result.smsBalance
      } catch (error) {
        console.log(error.message)
      }
    },
    // 创建周边司机活动
    async createAroundDriverApi(data) {
      try {
        const res = await createAroundDriver(data)
        if (res.code !== 200) return
        this.$router.push({ path: '/marketCenter/marketActivity' })
      } catch (error) {
        console.log(error.message)
      }
    },
    // 创建流失司机活动
    async createLostDriverApi(data) {
      try {
        const res = await createLostDriver(data)
        if (res.code !== 200) return
        this.$router.push({ path: '/marketCenter/marketActivity' })
      } catch (error) {
        console.log(error.message)
      }
    },
    // 获取接口方法
    async queryOrderList(gasId) { // 获取订单列表
      this.loading = true
      let params = { ...this.pageOptions, gasId, couponRuleStatus: 1 }
      try {
        const { code, result, totalRow } = await couponList(params)
        if (code !== 200) return
        if (this.multipleSelectionDia.length > 0) {
          this.multipleSelectionDia.map(item => {
            result.map(i => {
              if (i.id === item.id) {
                i.couponNum = item.couponNum
              }
            })
          })
        }
        this.tableData = result ? result : []
        this.allTotal = totalRow
      } catch (error) {
        console.log(error.message)
      } finally {
        this.loading = false
      }
    }
  },
  mounted() {
    this.texHasApi(this.passParams.gasId)
    const { gasId } = this.passParams
    this.queryOrderList(gasId)
  }
}
</script>

<style lang="less" scoped>
.block {
  display: flex;
  justify-content: flex-end;
}

.message {
  width: 100%;
  height: 120px;
  background: #F8F8F8;
  margin-top: 10px;
  padding: 20px 20px;
  display: flex;
  >div{
    width: 50%;
  }
  // .guess {
  //   display: flex;
  //   flex-direction: column;
  //   justify-content: flex-start;

  //   >span {
  //     margin-top: 10px;
  //   }
  // }
}

.check {
  height: 50px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.confirm {
  width: 100%;
  margin-top: 10px;
  display: flex;
  justify-content: center;
  align-items: center;

  /deep/.el-button {
    width: 122px;
  }
}

.phone {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 30px;
}

.mess {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  padding: 0 30px;
}

.sumbit {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

/deep/.el-dialog__title {
  font-size: 14px;
  color: #606266;
}
</style>
